<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Util;
use plugin\admin\app\constant\v1\CommonConstant;
use plugin\admin\app\service\v1\LineService;
use plugin\admin\app\service\v1\OptionService;
use plugin\admin\app\service\v1\OrderService;
use support\Request;
use support\Response;
use plugin\admin\app\model\V1OrderNode;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 订单节点
 */
class V1OrderNodeController extends Crud
{
    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 需要登录无需鉴权的方法
     * @var array
     */
    protected $noNeedAuth = [
        'select', 'orderNode', 'remark', 'group'
    ];

    /**
     * @var V1OrderNode
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new V1OrderNode;
    }

    /**
     * 浏览
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        $order_id = $request->input('order_id');
        $user_id = $request->input('user_id');
        $admin = admin();
        $config = OptionService::getConfigOrder();
        $line_list = "[]";
        $line_id = null;
        if ($user_id > 0) {
            list($line_list, $line_column) = LineService::select(['id', 'name']);
            $line_id = $line_list[0]['id'];
            $line_list = json_encode($line_list, JSON_UNESCAPED_UNICODE);
        }
        return view('v1-order-node/index', compact('order_id', 'user_id', 'admin', 'config', 'line_list', 'line_id'));
    }

    /**
     * 查询
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $admin = admin();
        if ($admin['user_status'] == CommonConstant::DEFAULT_2) {
            $where['user_id'] = $admin['id'];
        }
        $where['deleted'] = CommonConstant::DELETE_0;
        if (!isset($where['status'])) {
            $where['status'] = ['in', [CommonConstant::DEFAULT_0, CommonConstant::DEFAULT_1]];
        }
        $where['refund_status'] = ['in', [CommonConstant::DEFAULT_0, CommonConstant::DEFAULT_3]];
        $query = $this->doSelect($where, $field, $order);
        $query->with([
            'server' => function ($query) {
                $query->where('deleted', CommonConstant::DELETE_0)
                    ->select(['id','multi_port_status','multi_port']);
            }
        ]);
        $paginator = $query->paginate($limit);
        $total = $paginator->total();
        $items = $paginator->items();
        if ($items) {
            if($admin['user_status'] == CommonConstant::DEFAULT_1){
                foreach ($items as $item) {
                    Util::getSk5Port($item);
                }
            }
            if ($admin['user_status'] == CommonConstant::DEFAULT_2) {
                $lineId = isset($where['line_id']) && !empty($where['line_id']) ? $where['line_id'] : 0;

                $refundParams = orderService::surplusRefundNumber($admin, $lineId);
                $seconds = $refundParams['order_node_refund_time'] * 3600;
                $time = time();
                foreach ($items as $item) {
                    $later = $time;
                    $is_refund = 0; // 是否可以退款:0=否,1=是
                    if ($item->source == CommonConstant::DEFAULT_0 && $item->status == CommonConstant::DEFAULT_0 && in_array($item->refund_status, [CommonConstant::DEFAULT_0, CommonConstant::DEFAULT_3]) && !in_array($item->duration, [CommonConstant::TIME_0, CommonConstant::TIME_1, CommonConstant::TIME_2]) && $refundParams['surplus_refund_number'] > 0) {
                        $later = strtotime($item->created_at) + $seconds;
                        if ($time <= $later) {
                            $is_refund = 1;
                        }
                    }
                    $item->later = date('Y-m-d H:i', $later);
                    $item->is_refund = $is_refund;

                    Util::getSk5Port($item);
                }
            }
        }
        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('v1-order-node/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('v1-order-node/update');
    }


    /**
     * 资金记录-订单
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function orderNode(Request $request): Response
    {
        $id = $request->input('id');
        $info = Util::db()->table('wa_v1_user_money_log')->where('id', $id)->select(['type', 'order_id', 'order_node_ids'])->first();
        if (!$info) {
            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }

        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        unset($where['id']);
        $where['deleted'] = CommonConstant::DELETE_0;
        if ($info->type == CommonConstant::MONEY_LOG_TYPE_4) {
            $where['original_id'] = $info->order_id;
        }
        if ($info->type == CommonConstant::MONEY_LOG_TYPE_5) {
            $where['id'] = ['in', explode(',', $info->order_node_ids)];
        }
        $query = $this->doSelect($where, $field, $order);
        $query->with([
            'server' => function ($query) {
                $query->where('deleted', CommonConstant::DELETE_0)
                    ->select(['id','multi_port_status','multi_port']);
            }
        ]);
        $paginator = $query->paginate($limit);
        $total = $paginator->total();
        $items = $paginator->items();
        if ($items) {
            foreach ($items as $item) {
                Util::getSk5Port($item);
            }
        }
        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * 备注
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function remark(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $primary_key = $this->model->getKeyName();
            $ids = (array)$request->post($primary_key, []);
            $remark = $request->post('remark');
            if (!$ids) {
                return $this->json(1, '节点参数错误！');
            }
            if (!$remark) {
                return $this->json(1, '请输入备注！');
            }
            $this->model->whereIn($primary_key, $ids)->update(['remark' => $remark]);
            return $this->json(0, '备注成功！');
        }
    }

    /**
     * 分组
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function group(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $primary_key = $this->model->getKeyName();
            $ids = (array)$request->post($primary_key, []);
            $group = $request->post('group');
            if (!$ids) {
                return $this->json(1, '节点参数错误！');
            }
            if (!is_numeric($group) || $group < 0) {
                return $this->json(1, '请输入分组数字！');
            }
            $this->model->whereIn($primary_key, $ids)->update(['group' => $group]);
            return $this->json(0, '分组成功！');
        }
    }

}
